/*
 * Copyright 2010 Eligio Colutta
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.google.code.p2pxmppclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;


/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class Configurer {
	private static final Logger log = Logger.getLogger(Configurer.class.getCanonicalName());
	
	private static XMPPConnection connection = null;
	
	private static String username;
	private static String password;
	private static String host;
	private static String serviceName;
	private static int xmpp_port;
	private static int server_port;
	private static String[] recipients;
	
	private Configurer(){}
	
	
	private static void loadProperties(File propFile) throws FileNotFoundException, IOException{
		Properties props = new Properties();
		props.load(new FileInputStream(propFile));
		
		username = (String) props.get("xmpp_username");
		password = (String) props.get("xmpp_password");
		host = (String) props.get("xmpp_host");
		serviceName = (String) props.get("xmpp_serviceName");
		xmpp_port = Integer.parseInt((String) props.get("xmpp_port"));
		
		server_port = Integer.parseInt((String) props.get("notify_server_port"));
		String recipList = (String) props.get("recipients");
		
		if(recipList.length()>0){
			recipients = recipList.split(",");
		}
	}

	public static XMPPConnection getConnection(){
		return connection;
	}
	
	public static XMPPConnection getConnection(File f){
		try {
			loadProperties(f);
		} catch (FileNotFoundException e) {
			log.warning(e.getLocalizedMessage());
			System.exit(1);
		} catch (IOException e) {
			log.warning(e.getLocalizedMessage());
			System.exit(1);
		}
        ConnectionConfiguration connConfig = new ConnectionConfiguration(host, xmpp_port, serviceName);
        connConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
        connection = new XMPPConnection(connConfig);
		
        try {
            connection.connect();
            log.info("Connected to " + connection.getHost());
        } catch (XMPPException ex) {
            //ex.printStackTrace();
            log.warning("Failed to connect to " + connection.getHost());
            log.warning(ex.getLocalizedMessage());
            System.exit(1);
        }
        try {
        	SASLAuthentication.supportSASLMechanism("PLAIN", 0);
            connection.login(username, password);
            log.info("Logged in as " + connection.getUser());

            Presence presence = new Presence(Presence.Type.available);
            connection.sendPacket(presence);
            
        } catch (XMPPException ex) {
            // XMPPConnection only remember the username if login is succesful
            // so we can''t use connection.getUser() unless we log in correctly
            log.warning("Failed to log in as " + username);
            log.warning(ex.getLocalizedMessage());
            System.exit(1);
        }

		return connection;
	}

	public static PacketFilter getFilter(){
		AndFilter filters = new AndFilter();
		filters.addFilter(new PacketTypeFilter(Message.class));
		
		if(recipients!=null && recipients.length > 0){
			OrFilter recipientsFilter = new OrFilter();
			for(String recip : recipients){
				recipientsFilter.addFilter(new FromContainsFilter(recip));
			}
			filters.addFilter(recipientsFilter);
		}
		return filters;
	}


	public static String[] getRecipients() {
		return recipients;
	}


	public static int getServer_port() {
		return server_port;
	}
}
